﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using UserLoging.Dtos;
using UserLoging.Models;
using UserLoging.Services;

namespace UserLoging.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserLoginController : ControllerBase
    {
        public readonly IUserRepository _userRepository;
        public readonly IMapper _mapper;
        public UserLoginController(
            IUserRepository userRepository,
            IMapper mapper
            )
        {
            _userRepository = userRepository;
            _mapper = mapper;
        }
        [HttpPost(Name = "UserLogin")]
        public async Task<ReturnJson> UserLogin([FromBody] UserLogingDto userLogingDto)
        {
            User user = await _userRepository.GetUserByUserLoginDtoAsync(userLogingDto);
            if (user == null)
            {
                return new ReturnJson
                {
                    Status = 404,
                    Data = null,
                    Message = "用户不存在"
                };
            }
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("lixiannulixiannu"));
            var claims = new List<Claim>()
            {
            new Claim(ClaimTypes.Role,user.Permission.ToString()),
            new Claim(JwtRegisteredClaimNames.Sub,user.UserId.ToString()),
            };
            var token = new JwtSecurityToken
                (
                claims: claims,
                issuer: "https://localhost:44389/",
                audience: "https://localhost:8080/",
                expires: DateTime.Now.AddHours(5),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                );
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return new ReturnJson
            {
                Status = 200,
                Data = jwtToken,
                Message = "登录成功"
            };
        }
        [HttpGet("{userId}")]
        [Authorize]
        public async Task<ReturnJson> UserLogin(Guid userId)
        {
            if (!(await _userRepository.UserExistsAsync(userId))) 
            {
                return new ReturnJson {
                    Data = null,
                    Message = "用户不存在",
                    Status = 404
                };
            }
            //var role= User.FindFirst(d => d.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role")?.Value;
            User user = await _userRepository.GetUserByUserIdAsync(userId);

            return new ReturnJson
            {
                Data = _mapper.Map<EditUserFindDto>(user),
                Message = "请求成功",
                Status = 200

            };
        }
        [HttpPost("register")]
        [Authorize(Roles = "admin")]
        public async Task<ReturnJson> UserRegister([FromBody] UserRegisterDto userRegisterDto)
        {
            var user = _mapper.Map<User>(userRegisterDto);
            if (await _userRepository.UserExistsByUserNameAsync(userRegisterDto.UserName)) 
            {
                return new ReturnJson
                {
                    Status = 404,
                    Data = null,
                    Message = "用户名已存在"
                };
            }
            _userRepository.AddUser(user);
            await _userRepository.SaveAsync();
            return new ReturnJson {
                Status = 201,
                Data = userRegisterDto,
                Message = "添加成功"
            };
        }
        [HttpOptions]
        public IActionResult options() 
        {
            return Ok();
        }
        [HttpOptions("register")]
        public IActionResult Optionregister() 
        {
            return Ok();
        }
        [HttpOptions("{userId}")]
        public IActionResult Optionregisterbyid()
        {
            return Ok();
        }
    }
}
